********************************************************************
* This file generates the estimates reported in Table 4, Column 3. *
********************************************************************

*************************
* 0 Set path to files *
*************************
clear all
capture log close
set more off
set trace off
version 13.2
cd $main_directory

//Set predetermined values:
sca scale=10

//Load the data and the commands used in the estimation of the spatial demand model
use "Data_Belgium\Generated_data\baseline_demand_dataset.dta"
qui do "Command_files\spatial_demand_Q2.do"

//Calculate the total demand on the market
qui su Q2 if common==1
sca sumQ2=r(sum)
sca di sumQ2

//Calculate the total population on the market
bysort market_ID:  gen dup_market = cond(_N==1,0,_n)
qui su population if dup_market<2
sca sumPopulation=r(sum)
sca di sumPopulation

//Calculate total potential demand per capita as 10 times larger than the current value.
scalar gamma=10*sumQ2/sumPopulation
sca di gamma

//Calculate the market size (i.e. number of possible transactions)
gen market_size=gamma*population

//Define the product for which demand will be estimated (in this case non-realestate transactions).
gen firm_demand=Q2
drop if firm_demand==.
drop if firm_demand<=0
gen log_demand = log(firm_demand)

//Generate a unique numeric identifier for the market.
sort market_ID
egen market_ID_num = group(market_ID)

// Controls
global controls_utility distance lnNotPerOff start_not LDE Perc_Young Perc_Elderly log_income popdens
global controls_total firm_ID firm_demand market_ID_num market_size $controls_utility

//Estimate the demand for non-realestate transactions: this is column 3 of Table 4.
spatialdemand_logQ2 $controls_total
//Store the estimates for later use.
parmest,  saving("Estimates\spatial_demand_Q2", replace)
est store spatial_Q2
mat list e(b)
mata: betas_Q2=st_matrix("e(b)")'
mata: betas_Q2
mata: mata matsave "Estimates/betas_Q2" betas_Q2, replace
nlcom 1/(1+exp(-_b[nest]))
